from utils.common_import import *
from .model import AlertsQuerySchema
from config.prometheus_metric import PrometheusMetric

class Alerts(Resource):
    # @jwt_required()
    @request_arg_check(AlertsQuerySchema(), many=False, location="args")
    @exception_response()
    def get(self):
        # prometheus_uri = cluster_client.get_prometheus_uri()
        start_time = current_schema_instance['start_time'] / 1000
        end_time = current_schema_instance['end_time'] / 1000

        step = 300
        data = cluster_client.prometheus_client.query_range(PrometheusMetric.ALERTS, start_time, end_time, step = step)
        # data = query_range_prometheus_resource(prometheus_uri, query_exp, start_time, end_time, step = step)
        logger.info(data)
        alerts_list = []

        for alter in data['data']['result']:
            start = alter['values'][0]
            end = start
            for value in alter['values']:
                #两者之间不是连续的则认为是新的一次告警
                if start[0] != end[0] and  (value[0] - end[0]) !=  step:
                    alerts_list.append(dict(alertname=alter["metric"]["alertname"],
                                            instance=alter["metric"]["instance"],
                                            start=start[0]*1000, end=end[0]*1000))
                    start = value
                #已经到最后一次告警
                elif value[0] == alter['values'][-1][0]:
                    alerts_list.append(dict(alertname=alter["metric"]["alertname"],
                                            instance=alter["metric"]["instance"],
                                            start=start[0]*1000, end=value[0]*1000))

                end = value

        return make_success_response(alerts_list)
